﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.LanguageWire.LanguageWireAPI;
using LWAPI = iLangl.LanguageWire.LanguageWireAPI;
using log4net;

namespace iLangl.LanguageWire.DAL.LanguageWireDAL.RealStorage
{
	public class BaseStorageLWAPI
	{
		private ILog _log = null;
		protected virtual ILog log
		{
			get
			{
				if (_log == null)
				{
					_log = LogManager.GetLogger(this.GetType());
				}
				return _log;
			}
		}


		private APIExtensionServiceClient _service = null;
		protected APIExtensionServiceClient service
		{
			get
			{
				if (_service == null)
				{
					_service = new APIExtensionServiceClient();
				}

				return _service;
			}
		}


		protected static StartSessionResponse session = null;
		public void StartSession()
		{
			if (session == null)
			{
				StartSessionRequest request = new StartSessionRequest();
				request.UserName = LWStorageConfiguration.Instance.UserName;
				request.UserPassword = LWStorageConfiguration.Instance.Password;


				session = service.StartSession(request);
				LogResponse(session);
			}
		}

		protected void SubscribeRequest(AuthenticationRequest request)
		{
			request.SessionId = session.SessionId;
		}

		public void StopSession()
		{
			StopSessionRequest ssrequest = new StopSessionRequest();
			ssrequest.SessionId = session.SessionId;

			service.StopSession(ssrequest);
			session = null;
		}

		protected void LogResponse(BaseResponse response)
		{
			IAlert alert =  Facade.Instance.AlertManager.CreateAlert(this);
			
			foreach (LWAPI.Error error in response.Errors)
			{
				IError ierror = new Error(String.Format("{0} - {1}", error.Code, error.Message),
					error.UserHint,
					eSeverity.High);

				alert.AddError(ierror);
			}

			Facade.Instance.AlertManager.RaiseAlert(alert);
		}
	}
}
